﻿package net.wangit.view.unit.sum;

import java.util.ArrayList;
import java.util.List;

import net.wangit.Row;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.unit.UnitComponent;


public abstract class SumItem {

	private static final String GROUP_VALUE = "*";
	protected int begin;
	protected int end;
	protected String sumName;
	private String text;
	private String textName;
	private String groupName;
	private int sumValueIndex;
	private String groupValue;
	private List values;

	protected SumItem(UnitComponent uc, int begin, int end, String configs[]) {
		sumValueIndex = 0;
		groupValue = null;
		values = new ArrayList();
		this.begin = begin;
		this.end = end;
		sumName = configs[1].trim().toLowerCase();
		int index = sumName.indexOf("=");
		if (index > 0)
			sumName = sumName.substring(0, index).trim();
		String textConfig = configs[0];
		index = textConfig.indexOf("/");
		if (index > 0) {
			text = textConfig.substring(0, index);
			textName = textConfig.substring(index + 1).trim().toLowerCase();
		} else if (index < 0 && !Checker.isEmpty(textConfig))
			text = textConfig;
		if (configs.length > 2)
			groupName = configs[2].trim().toLowerCase();
	}

	public void doSum(int index, Row row) {
		if (index >= begin && (end < 0 || index < end))
			sum(index, row);
	}

	public String getText(SumValue sv) {
		String groupValue = sv.getGroupValue();
		if (!Checker.isEmpty(groupValue) && !Checker.isEmpty(text))
			return StringUtil.replace(text, "*", groupValue);
		else
			return text;
	}

	public String getTextName() {
		return textName;
	}

	public String getSumName() {
		return sumName;
	}

	protected void sum(int index, Row row) {
		if (groupName != null) {
			if (groupValue == null)
				groupValue = row.get(groupName, "");
			String tempGroupValue = row.get(groupName, "");
			if (!groupValue.equals(tempGroupValue)) {
				groupValue = tempGroupValue;
				sumValueIndex++;
			}
		}
		SumValue sv = getSumValue(sumValueIndex);
		sum(sv, row);
		if (groupName != null) {
			sv.setRowIndex(index);
			sv.setGroupValue(groupValue);
		}
	}

	protected abstract void sum(SumValue sumvalue, Row row);

	protected SumValue getSumValue(int valueIndex) {
		if (valueIndex >= values.size()) {
			SumValue row = new SumValue();
			values.add(row);
		}
		return (SumValue) values.get(valueIndex);
	}

	public List getSumValues() {
		return values;
	}
}
